package com.op.teachingliteapp.common.api.smartpan;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

public class CmdForm {
	public final static String CMD_LIST = "list";
	public final static String CMD_DELETE_FOLDER = "delfolder";
	public final static String CMD_CREATE_FOLDER = "createfolder";
	public final static String CMD_UPLOAD = "upload";
	public final static String CMD_UPDATA = "updata";
	public final static String CMD_DOWNLOAD = "download";

	private Map<String, String> paramsMap;

	/**
	 * 构造函数
	 */
	private CmdForm(String ownerID, String path, String operation, String data, String data2) {
		paramsMap = new HashMap<String, String>();
		paramsMap.put("ownerid", ownerID);
		paramsMap.put("path", path);
		paramsMap.put("operation", operation);
		paramsMap.put("data", data);
		paramsMap.put("data2", data2);
	}

	/**
	 * 生成cmd的Json参数
	 */
	public static String generateJsonCmd(String ownerID, String path, String operation, String data, String data2) {
		CmdForm cmdForm = new CmdForm(ownerID, path, operation, data, data2);
		JSONObject cmdJson = new JSONObject(cmdForm.getParamsMap());
		return cmdJson.toString();
	}

	public static String generateJsonCmd(String ownerID, String path, String operation, String data) {
		CmdForm cmdForm = new CmdForm(ownerID, path, operation, data, "");
		JSONObject cmdJson = new JSONObject(cmdForm.getParamsMap());
		return cmdJson.toString();
	}

	public static String generateJsonCmd(String ownerID, String path, String operation) {
		CmdForm cmdForm = new CmdForm(ownerID, path, operation, "", "");
		JSONObject cmdJson = new JSONObject(cmdForm.getParamsMap());
		return cmdJson.toString();
	}

	/**
	 * 读取返回值
	 */
	public static String getOutputMessage(String output) {
		try {
			JSONObject outputJson = new JSONObject(output);
			return outputJson.getString("error_msg");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 读取返回值，返回列表
	 */
	public static boolean fillEntityBeanList(List<EntityBean> entityBeanList, String output) {

		try {
			JSONArray jsonArray = new JSONArray(output);

			JSONArray entityJsonList = jsonArray.getJSONObject(0).getJSONArray("subNodeList");
			for (int i = 0; i < entityJsonList.length(); i++) {
				JSONObject entityJsonObject = entityJsonList.getJSONObject(i);
				EntityBean entityBean = new EntityBean(entityJsonObject);
				entityBeanList.add(entityBean);
			}
			return true;
		} catch (Exception e) {
			return false;
		}

	}

	public Map<String, String> getParamsMap() {
		return paramsMap;
	}

}
